<template>
  <view class="job-container">
    <!-- 分类标签 -->
    <view class="category-tabs">
      <view v-for="(category, index) in categories" :key="index" class="category-item"
            :class="[activeCategory === category ? 'active' : '']" @click="switchCategory(category)">
        <text class="category-text">{{ category }}</text>
      </view>
    </view>
    <view class="search-box">
      <u-search placeholder="请输入关键词" v-model="keyword"></u-search>
    </view>
    <!-- 题库列表 -->
    <scroll-view class="qs-list" scroll-y="true" refresher-enabled @refresherrefresh="onRefresh"
                 @scrolltolower="loadMore">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 无权限状态 -->
      <view v-else-if="!hasPermission" class="no-permission-state">
        <image src="/static/image/no_permission.png" class="permission-illustration" mode="aspectFit"></image>

        <view class="permission-text">
          <text class="permission-title">没有权限</text>
          <text class="permission-desc">可以通过邀请好友可解锁权限</text>
        </view>

        <view class="invite-btn" @click="inviteFriends">
          <text class="invite-text">立即邀请</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else-if="jobList.length === 0" class="empty-state">
        <image src="/static/image/empty_order.png" class="empty-icon" mode="aspectFit"></image>
        <text class="empty-text">暂无岗位</text>
      </view>

      <!-- 岗位列表 -->
      <view v-else class="job-list-container">
        <view v-for="(job, index) in jobList" :key="job.id" class="job-item" @click="viewJobDetail(job)">
          <view class="job-bg"></view>

          <!-- 岗位标题 -->
          <view class="job-title">
            <text class="title-text">{{ job.positionName }}</text>
            <text class="position-code">({{ job.positionCode }})</text>
          </view>

          <!-- 岗位信息 -->
          <view class="job-info" v-if="categories === currentYear">
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">报考地区:</text>
                <text class="info-value">{{ job.recruitCount }}人</text>
              </view>
            </view>
            <view class="info-row">
              <view class="info-item">
                <text class="info-label">报考类型:</text>
                <text class="info-value">{{ job.positionType }}</text>
              </view>
            </view>
          </view>
		  
		  <view class="job-info" v-else>
		    <view class="info-row">
		      <view class="info-item">
		        <text class="info-label">招录人数:</text>
		        <text class="info-value">{{ job.recruitCount }}人</text>
		      </view>
		    </view>
		    <view class="info-row">
		      <view class="info-item">
		        <text class="info-label">岗位类型:</text>
		        <text class="info-value">{{ job.positionType }}</text>
		      </view>
		    </view>
		  			<view class="info-row">
		  			  <view class="info-item">
		  			    <text class="info-label">分数线:</text>
		  			    <text class="info-value">{{ job.positionType }}</text>
		  			  </view>
		  			</view>
		  			<view class="info-row">
		  			  <view class="info-item">
		  				<text class="info-label">须应届:</text>
		  				<text class="info-value">{{ job.positionType }}</text>
		  			  </view>
		  			</view>
		  			<view class="info-row">
		  			  <view class="info-item">
		  				<text class="info-label">须党员:</text>
		  				<text class="info-value">{{ job.positionType }}</text>
		  			  </view>
		  			</view>
		  			<view class="info-row">
		  			  <view class="info-item">
		  				<text class="info-label">工作经验:</text>
		  				<text class="info-value">{{ job.positionType }}</text>
		  			  </view>
		  			</view>
		  </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore && hasPermission" class="load-more" @click="loadMore">
        <text class="load-more-text">加载更多</text>
      </view>
      <view v-else-if="!hasMore && hasPermission" class="no-more">
        <text class="no-more-text">没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
		currentYear: new Date().getFullYear(),
      activeCategory: 2024,
      hasMore: false,
      loading: false,
      hasPermission: true, // 是否有权限
      currentPage: 1,
      categories: [
        2024,
        2023,
        2022,
        2021
      ],
      keyword: '',
      jobList: [
        {
          id: 1,
          positionName: 'A',
          positionCode: 'ZO209100',
          recruitCount: 3,
          positionType: '金融岗',
          scoreLine: 120,
          requireGraduate: false,
          requirePartyMember: false,
          requireWorkExperience: true,
          workExperienceYears: 2
        },
        {
          id: 2,
          positionName: 'B',
          positionCode: 'ZO209101',
          recruitCount: 5,
          positionType: '技术岗',
          scoreLine: 125,
          requireGraduate: true,
          requirePartyMember: true,
          requireWorkExperience: false,
          workExperienceYears: 0
        }
      ]
    }
  },
  methods: {
    // 切换分类
    switchCategory(index) {
      this.activeCategory = index;
      uni.showLoading({
        title: '加载中...'
      });

      // 重置页码
      this.currentPage = 1;

      // 根据分类加载数据
      const year = this.categories[index];
      const params = {
        user_id: this.userInfo.id,
        pageNo: this.currentPage,
        pageSize: 10,
        year: year
      };

      this.$api.getJobList(params).then(res => {
        uni.hideLoading();
        if (res && res.list) {
          this.jobList = res.list;
          this.hasMore = this.jobList.length < res.total;
        }
      }).catch(error => {
        uni.hideLoading();
        console.error('获取岗位列表失败:', error);
        uni.showToast({
          title: '获取岗位列表失败',
          icon: 'none'
        });
      });
    },

    // 查看岗位详情
    viewJobDetail(job) {
      uni.navigateTo({
        url: `/pages/job/detail?id=${job.id}&positionName=${job.positionName}`
      });
    },

    // 根据表单数据搜索岗位
    searchJobs(formData) {
      this.loading = true;
      uni.showLoading({
        title: '搜索中...'
      });

      // 构建搜索参数
      const params = {
        regions: formData.regions,
        position: formData.position,
        isGraduate: formData.isGraduate,
        isPartyMember: formData.isPartyMember,
        hasGrassrootsWork: formData.hasGrassrootsWork,
        queryType: formData.queryType,
        selectedProvinces: formData.selectedProvinces,
        selectedCities: formData.selectedCities,
        selectedDistricts: formData.selectedDistricts,
        pageNo: 1,
        pageSize: 10
      };

      // 调用搜索API
      this.$api.searchJobs(params).then(res => {
        this.loading = false;
        uni.hideLoading();

        if (res && res.list) {
          this.jobList = res.list;
          this.hasMore = this.jobList.length < res.total;
        } else {
          this.jobList = [];
          this.hasMore = false;
        }
      }).catch(error => {
        this.loading = false;
        uni.hideLoading();
        console.error('搜索岗位失败:', error);
        uni.showToast({
          title: '搜索失败',
          icon: 'none'
        });
      });
    },

    // 下拉刷新
    onRefresh() {
      uni.showLoading({
        title: '刷新中...'
      });

      // 重新加载岗位列表
      this.loadJobList();
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return;

      this.loading = true;
      uni.showLoading({
        title: '加载中...'
      });

      // 计算下一页
      this.currentPage += 1;
      const params = {
        user_id: this.userInfo.id,
        pageNo: this.currentPage,
        pageSize: 10
      };

      this.$api.getJobList(params).then(res => {
        this.loading = false;
        uni.hideLoading();

        if (res && res.list && res.list.length > 0) {
          this.jobList = [...this.jobList, ...res.list];
          this.hasMore = this.jobList.length < res.total;
        } else {
          this.hasMore = false;
        }
      }).catch(error => {
        this.loading = false;
        uni.hideLoading();
        console.error('加载更多岗位失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
    },

    // 初始化数据
    initData() {
      this.loading = true;
      uni.showLoading({
        title: '加载中...'
      });

      // 调用API获取岗位列表
      this.loadJobList();
    },

    // 加载岗位列表
    loadJobList() {
      // 重置页码
      this.currentPage = 1;

      const params = {
        user_id: this.userInfo.id,
        pageNo: this.currentPage,
        pageSize: 10
      };

      this.$api.getJobList(params).then(res => {
        this.loading = false;
        uni.hideLoading();

        if (res && res.list) {
          this.jobList = res.list;
          this.hasMore = this.jobList.length < res.total;
        }
      }).catch(error => {
        this.loading = false;
        uni.hideLoading();
        console.error('获取岗位列表失败:', error);
        uni.showToast({
          title: '获取岗位列表失败',
          icon: 'none'
        });
      });
    },



    // 邀请好友
    inviteFriends() {
      // 检查用户信息
      if (!this.userInfo || !this.userInfo.id) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }

      // 显示分享菜单
      uni.showActionSheet({
        itemList: ['分享给好友', '分享到朋友圈'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 分享给好友
            this.shareToFriend();
          } else if (res.tapIndex === 1) {
            // 分享到朋友圈
            this.shareToTimeline();
          }
        },
        fail: (err) => {
          console.error('显示分享菜单失败:', err);
        }
      });
    },

    // 分享给好友
    shareToFriend() {
      // 触发微信分享给好友
      // 这里会调用 onShareAppMessage 方法
      uni.showToast({
        title: '请点击右上角分享',
        icon: 'none',
        duration: 2000
      });
    },

    // 分享到朋友圈
    shareToTimeline() {
      // 触发微信分享到朋友圈
      // 这里会调用 onShareTimeline 方法
      uni.showToast({
        title: '请点击右上角分享到朋友圈',
        icon: 'none',
        duration: 2000
      });
    }
  },
  onLoad(options) {
    // 接收从search页面传递过来的数据
    if (options.formData) {
      try {
        const formData = JSON.parse(decodeURIComponent(options.formData));
        console.log('接收到的表单数据:', formData);
        // 这里可以根据formData进行查询
        this.searchJobs(formData);
      } catch (error) {
        console.error('解析表单数据失败:', error);
      }
    } else {
      this.initData();
    }
  },

  // 微信分享配置
  onShareAppMessage() {
    if (!this.userInfo || !this.userInfo.id) {
      return {
        title: '邀请好友解锁题库权限',
        path: '/pages/invite/invite'
      };
    }

    return {
      title: '邀请好友解锁题库权限',
      desc: '邀请好友注册，即可解锁更多题库权限，一起学习进步！',
      path: `/pages/invite/invite?user_id=${this.userInfo.id}&source=qs`,
      imageUrl: '/static/image/share_cover.png'
    };
  },

  onShareTimeline() {
    if (!this.userInfo || !this.userInfo.id) {
      return {
        title: '邀请好友解锁题库权限',
        path: '/pages/invite/invite'
      };
    }

    return {
      title: '邀请好友解锁题库权限',
      desc: '邀请好友注册，即可解锁更多题库权限，一起学习进步！',
      path: `/pages/invite/invite?user_id=${this.userInfo.id}&source=qs`,
      imageUrl: '/static/image/share_cover.png'
    };
  }
}
</script>

<style lang="scss">
.job-container {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  .search-box {
    background-color: #fff;
    padding:0 24rpx 24rpx 24rpx;
  }
}

// 顶部搜索栏
.header {
  //position: fixed;
  //top: 0;
  //left: 0;
  //right: 0;
  //z-index: 1000;
  background-color: #fff;
  //padding-right: 140rpx;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 32rpx;
  }

  .search-container {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 20rpx;
    margin-right: 20rpx;

    .search-box {
      flex: 1;
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      bqs-radius: 50rpx;
      padding: 0 24rpx;
      height: 72rpx;
      border: 2rpx solid #A6A6A6;
      position: relative;

      .search-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 16rpx;
      }

      .search-input {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }

      .search-placeholder {
        color: #999;
      }
    }

    .search-btn {
      color: #333;

      .search-btn-text {
        font-size: 28rpx;
      }

      &:active {
        background-color: #555;
      }
    }
  }
}

// 分类标签
.category-tabs {
  display: flex;
  align-items: center;
  padding: 24rpx 32rpx;
  background-color: #fff;
  gap: 40rpx;
  bqs-bottom: 2rpx solid #f0f0f0;
  overflow-x: auto;

  .category-item {
    flex-shrink: 0;
    position: relative;
    padding-bottom: 16rpx;

    .category-text {
      font-size: 28rpx;
      color: #666;
      font-weight: 400;
    }

    &.active {
      .category-text {
        color: #333;
        font-weight: 500;
      }

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 4rpx;
        background-color: #539DF3;
        bqs-radius: 2rpx;
      }
    }

    &:active {
      opacity: 0.7;
    }
  }
}

// 订单列表
.qs-list {
  flex-grow: 1;
  padding-top: 24rpx;
  width: 100%;
  box-sizing: bqs-box;
}

// 加载状态
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 120rpx 32rpx;

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}

// 无权限状态
.no-permission-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 32rpx;
  border-radius: 16rpx;
  margin: 24rpx 32rpx;

  .permission-illustration {
    position: relative;
    width: 480rpx;
    height: 480rpx;
  }

  .permission-text {
    text-align: center;
    margin-bottom: 40rpx;

    .permission-title {
      font-size: 36rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 16rpx;
      display: block;
    }

    .permission-desc {
      font-size: 28rpx;
      color: #666;
      line-height: 1.4;
      display: block;
    }
  }

  .invite-btn {
    width: 280rpx;
    height: 70rpx;
    background: #539DF3;
    border-radius: 44rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    .invite-text {
      font-size: 32rpx;
      color: #fff;
      font-weight: bold;
    }

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 4rpx 12rpx rgba(83, 157, 243, 0.3);
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 32rpx;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #ccc;
  }
}

.job-list-container {
  padding: 0 32rpx;
}

.job-item {
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 32rpx;
  overflow: hidden;
  position: relative;

  .job-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    z-index: 1;
    background-color: #fff;
  }

  .job-shadow {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 50%;
    top: 0;
    z-index: 2;
    background: linear-gradient(90deg, rgba(83, 157, 243, 0) 0%, rgba(83, 157, 243, 0.3) 100%);
  }
}

// 岗位标题
.job-title {
  margin-bottom: 24rpx;
  position: relative;
  z-index: 3;
  display: flex;
  align-items: center;
  gap: 12rpx;

  .title-text {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    line-height: 1.4;
  }

  .position-code {
    font-size: 2rpx;
    color: #333;
    font-weight: bold;
    line-height: 1.4;
  }
}

// 岗位信息
.job-info {
  position: relative;
  z-index: 3;

  .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .info-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex: 1;

    .info-label {
      font-size: 28rpx;
      color: #333;
      white-space: nowrap;
    }

    .info-value {
      font-size: 28rpx;
      color: #333;

      &.required {
        color: #e74c3c;
        font-weight: bold;
      }
    }
  }
}

// 加载更多
.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  margin: 40rpx 0;

  .load-more-text {
    font-size: 28rpx;
    color: #666;
  }

  &:active {
    opacity: 0.7;
  }
}

.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  margin: 40rpx 0;

  .no-more-text {
    font-size: 24rpx;
    color: #ccc;
  }
}
</style>
